# -*- coding: utf-8 -*-
"""
@ Created on 2024-06-14 12:23
---------
@summary: 用户CRUD操作
---------
@author: Lsaiah
"""

from tortoise import fields
from tortoise.models import Model
from tortoise.contrib.pydantic import pydantic_model_creator
from datetime import datetime
from typing import Optional, List, Dict, Any


class User(Model):
    """用户模型"""
    id = fields.IntField(pk=True, description="用户ID")
    username = fields.CharField(max_length=50, unique=True, description="用户名")
    email = fields.CharField(max_length=255, unique=True, null=True, description="邮箱")
    phone = fields.CharField(max_length=20, unique=True, null=True, description="手机号")
    dept_id = fields.IntField(null=True, description="部门ID")
    hashed_password = fields.CharField(max_length=255, description="加密密码")
    full_name = fields.CharField(max_length=255, null=True, description="全名")
    avatar = fields.CharField(max_length=500, null=True, description="头像")
    is_active = fields.BooleanField(default=True, description="是否激活")
    is_superuser = fields.BooleanField(default=False, description="是否超级用户")
    last_login = fields.DatetimeField(null=True, description="最后登录时间")
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    updated_at = fields.DatetimeField(auto_now=True, description="更新时间")

    class Meta:
        table = "system_user"
        table_description = "系统用户表"

    def __str__(self):
        return f"User(id={self.id}, username={self.username})"


#  Pydantic 模型
User_Pydantic = pydantic_model_creator(User, name="User")
UserIn_Pydantic = pydantic_model_creator(
    User, 
    name="UserIn", 
    exclude_readonly=True,
    exclude=("id", "created_at", "updated_at", "last_login")
)
UserUpdate_Pydantic = pydantic_model_creator(
    User, 
    name="UserUpdate", 
    exclude_readonly=True,
    exclude=("id", "created_at", "updated_at")
)
UserLogin_Pydantic = pydantic_model_creator(
    User,
    name="UserLogin",
    include=("username", "hashed_password")
)


class UserCRUD:
    """用户CRUD操作类"""
    
    @staticmethod
    async def create(user_data: Dict[str, Any]) -> User:
        """创建用户"""
        return await User.create(**user_data)
    
    @staticmethod
    async def get_by_id(id: int) -> Optional[User]:
        """根据ID获取用户"""
        return await User.get_or_none(id=id)
    
    @staticmethod
    async def get_user_by_id(user_id: int) -> Optional[User]:
        """根据ID获取用户（兼容旧接口）"""
        return await User.get_or_none(id=user_id)
    
    @staticmethod
    async def get_user_by_username(username: str) -> Optional[User]:
        """根据用户名获取用户"""
        return await User.get_or_none(username=username)
    
    @staticmethod
    async def get_user_by_email(email: str) -> Optional[User]:
        """根据邮箱获取用户"""
        return await User.get_or_none(email=email)
    
    @staticmethod
    async def get_list(
        skip: int = 0, 
        limit: int = 10, 
        search: Optional[str] = None,
        **filters
    ) -> List[User]:
        """获取用户列表"""
        query = User.all()
        
        if search:
            query = query.filter(
                username__icontains=search
            ) | query.filter(
                email__icontains=search
            ) | query.filter(
                full_name__icontains=search
            )
        
        # 处理其他过滤条件
        for key, value in filters.items():
            if value is not None:
                query = query.filter(**{key: value})
        
        return await query.offset(skip).limit(limit).order_by("-created_at")
    
    @staticmethod
    async def count_list(
        search: Optional[str] = None,
        **filters
    ) -> int:
        """统计用户数量"""
        query = User.all()
        
        if search:
            query = query.filter(
                username__icontains=search
            ) | query.filter(
                email__icontains=search
            ) | query.filter(
                full_name__icontains=search
            )
        
        # 处理其他过滤条件
        for key, value in filters.items():
            if value is not None:
                query = query.filter(**{key: value})
        
        return await query.count()
    
    @staticmethod
    async def update(user_id: int, update_data: Dict[str, Any]) -> Optional[User]:
        """更新用户"""
        user = await User.get_or_none(id=user_id)
        if user:
            await user.update_from_dict(update_data)
            await user.save()
        return user
    
    @staticmethod
    async def update_last_login(user_id: int) -> bool:
        """更新用户最后登录时间"""
        user = await User.get_or_none(id=user_id)
        if user:
            from datetime import datetime
            user.last_login = datetime.now()
            await user.save()
            return True
        return False
    
    @staticmethod
    async def delete(user_id: int) -> bool:
        """删除用户"""
        user = await User.get_or_none(id=user_id)
        if user:
            await user.delete()
            return True
        return False
    
    @staticmethod
    async def update_last_login(user_id: int) -> None:
        """更新最后登录时间"""
        await User.filter(id=user_id).update(last_login=datetime.now())
